package ingredientsClient;

import javax.xml.soap.SOAPMessage;
import javax.xml.soap.MessageFactory;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.Dispatch;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;

public class Client {
    
    private Service service;
    private String url;
    private String nameSpace;
    private String serviceName;
    private String portName;
    
    private QName serviceQname;
    private QName portQname;

    private Dispatch<SOAPMessage> dispatch;
    
    
    public Client() {
    }

    public Client( String url, String serviceName, String portName, String nameSpace )
    {
        this.url = url;
        this.nameSpace = nameSpace;
        this.serviceName = serviceName;
        this.portName = portName;
        
        serviceQname = new QName( this.nameSpace, this.serviceName );
        portQname = new QName( this.nameSpace, this.portName );
        
        service = Service.create(serviceQname);
        service.addPort(portQname, javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_BINDING,nameSpace);
	
        dispatch = service.createDispatch(portQname, SOAPMessage.class, javax.xml.ws.Service.Mode.MESSAGE);
    }
    
    public SOAPMessage invoke( String soapRequest )
    {
        SOAPMessage request = makeSOAPMessage( soapRequest );
        SOAPMessage response = dispatch.invoke( request );
        
        return response;
    }
    
    public SOAPMessage invoke( SOAPMessage message )
    {
        SOAPMessage response = dispatch.invoke( message );
        
        return response;
    }
    
    private SOAPMessage makeSOAPMessage( String msg )
    {
	try
        {
            MessageFactory factory = MessageFactory.newInstance();
            SOAPMessage message = factory.createMessage();
            message.getSOAPPart().setContent((Source) new StreamSource(new StringReader(msg)));
            message.saveChanges();
            return message;
	}
	catch (Exception e) {
	    return null;
	}
    }
}
